<template>
  <el-dialog
    :title="dialogObj.title"
    append-to-body
    :visible.sync="dialogObj.show"
    :close-on-click-modal="false"
    width="60%"
    class="abow_dialog"
  >
    <el-form
      ref="form"
      :model="form"
      status-icon
      label-width="140px"
      :rules="rules"
      :disabled="dialogObj.view == true"
      v-if="dialogObj.show"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称：" prop="productName">
            <el-input
              v-model="form.productName"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.productName"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品简介：" prop="description">
            <el-input
              v-model="form.description"
              style="width:200px;"
              :placeholder="placeholderTips.description"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品分类：" prop="categoryId">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择类型"
              size="mini"
              :disabled="dialogObj.form.isDraft != 1"
            >
              <el-option
                v-for="(data, index) in prouductSelect"
                :key="index"
                :label="data.categoryName"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品价格(元)：" prop="currentPrice">
            <el-input-number
              v-model="form.currentPrice"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.currentPrice"
              size="mini"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品规格名称：" prop="specificationName">
            <el-input
              v-model="form.specificationName"
              style="width:200px;"
              :placeholder="placeholderTips.specificationName"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品规格类型：" prop="specificationType">
            <el-input
              v-model="form.specificationType"
              style="width:200px;"
              :placeholder="placeholderTips.specificationType"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="库存量（个）：" prop="stock">
        <el-input-number
          v-model="form.stock"
          style="width:200px;"
          :disabled="dialogObj.form.isDraft != 1"
          :placeholder="placeholderTips.stock"
          size="mini"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="关联活动：" required>
        <el-cascader-multi
          v-model="productActivityList"
          :data="ActivityList"
          filterable
          style="width:500px;"
          children-key="activityDates"
          placeholder="请选择活动"
          :only-last="true"
          @change="handleActivity"
          separator="/"
          no-data-text="无数据"
        >
        </el-cascader-multi>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品图：" prop="imgUrl">
            <upload-picture
              :imageValue="form.imgUrl"
              @handleSuccess="handleSuccess"
            >
            </upload-picture>
            <span style="color:red;font-size:12px">推荐尺寸： 510*312</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品详情图：" prop="detailImg">
            <upload-picture
              :imageValue="form.detailImg"
              @handleSuccess="handleSuccessDetail"
            >
            </upload-picture>
            <span style="color:red;font-size:12px">推荐尺寸： 1065*552</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序码：" prop="sort">
            <el-input
              v-model="form.sort"
              style="width:200px;"
              :placeholder="placeholderTips.sort"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="限购数量：" prop="purchaseLimit">
            <el-input
              v-model="form.purchaseLimit"
              style="width:200px;"
              :placeholder="placeholderTips.purchaseLimit"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="楼层：" required>
        <el-checkbox-group v-model="floor" @change="changeCheck">
          <el-checkbox :label="1">F1</el-checkbox>
          <el-checkbox :label="2">F2</el-checkbox>
          <el-checkbox :label="3">F3</el-checkbox>
          <el-checkbox :label="4">F4</el-checkbox>
          <el-checkbox :label="5">F5</el-checkbox>
          <el-checkbox :label="6">场外</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="上架时间：">
        <el-radio-group v-model="onTime">
          <el-radio :label="1">立即上架</el-radio>
          <el-radio :label="2">指定时间</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定时间：" prop="shelfTime" v-if="onTime == 2">
        <el-date-picker
          v-model="form.shelfTime"
          format="yyyy-MM-dd HH"
          type="datetime"
          placeholder="选择日期时间"
          size="mini"
          :picker-options="onPickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下架时间：">
        <el-radio-group v-model="offTime">
          <el-radio :label="1">指定时间</el-radio>
          <el-radio :label="2">长期不下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定时间：" prop="offShelfTime" v-if="offTime == 1">
        <el-date-picker
          v-model="form.offShelfTime"
          format="yyyy-MM-dd HH"
          type="datetime"
          placeholder="选择日期时间"
          size="mini"
          :picker-options="offPickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="详情描述：">
        <image-text :tableData="tableData" @handleTableDate="handleTableDate">
        </image-text>
      </el-form-item>
    </el-form>
    <div class="operate-footer">
      <el-button
        type="primary"
        @click="sub(1)"
        size="mini"
        v-if="dialogObj.form.isDraft != 4 && dialogObj.view != true"
        >保存为草稿</el-button
      >
      <el-button
        type="primary"
        @click="sub(2)"
        size="mini"
        v-if="dialogObj.view != true"
        >确 定</el-button
      >
      <el-button
        @click="dialogObj.show = false"
        size="mini"
        v-if="dialogObj.view != true"
        >取 消</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import Cookie from "@u/cookie";
import { _debounce } from "@u/debounce";
import {
  placeholderTips,
  validateString,
  validateNumber,
  validateNumEmpty,
  validateTemplate,
  validateTemplateActivity,
  validateTemplatePicture,
  validateTemplateFloor,
  validateTemplateContent,
  validateTemplateTime,
  validateNumInt,
  validateStringSpecial
} from "@u/validate";
import imageText from "@c/imageText";
import uploadPicture from "@c/uploadPicture";
import {
  getProductSelectApi,
  updateGoodsInfoApi,
  addGoodsInfoApi,
  getLocalActivityApi
} from "@s/api";
import timeFormat from "@u/timeFormat";
// import Cookie from "@u/cookie";
export default {
  name: "dialogCom",
  props: ["dialogObj"],
  components: {
    imageText,
    uploadPicture
  },
  data() {
    return {
      // productActivityList: [[1,3], [4]],
      productActivityList: [],
      options: [
        {
          value: 1,
          label: "东南",
          activityDates: [
            {
              value: 2,
              label: "上海"
            },
            {
              value: 3,
              label: "22上海"
            }
          ]
        },
        {
          value: 4,
          label: "东22南",
          activityDates: [
            {
              value: 5,
              label: "上海"
            },
            {
              value: 6,
              label: "上海"
            }
          ]
        }
      ],
      placeholderTips: placeholderTips,
      onTime: 1, //1 立即上架  2 指定时间
      offTime: 2, //1 指定时间  2 长期不下架
      goodStatus: "", // 1 草稿  2 非草稿
      // 上架日期限制
      onPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 下架日期限制
      offPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      tableData: [
        {
          imageUrl: "",
          description: ""
        }
      ],
      prouductSelect: [],
      ActivityList: [],
      // activity: [],
      floor: [],
      form: {
        productorCategory: 2, // 1 餐饮
        categoryId: "", // 商品分类 id
        currentPrice: "", // 价格
        description: "", // 商品描述
        imgUrl: "", // 商品图片
        detailImg: "", // 商品详情图片
        detail: "", // 商品详情
        isDraft: "", // 商品状态 1草稿 2 待上架 3 上架中 4 已下架
        offShelfTime: "", // 下架时间
        productName: "", // 商品名字
        purchaseLimit: "", // 限购数量
        shelfTime: "", // 上架时间
        sort: "", // 排序码
        stock: "", //  库存
        specificationName: "",
        specificationType: "",
        referActivityId: "",
        // referActivityDate: "",
        productActivityList: "",
        referActivityName: "",
        venueFloor: "" // 楼层
      },
      rules: {
        sort: [{ validator: validateNumEmpty }],
        categoryId: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateTemplate }
        ],
        currentPrice: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { validator: validateNumber }
        ],
        description: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateString }
        ],
        imgUrl: [
          { required: true, message: "请上传图片", trigger: "change" },
          { validator: validateTemplatePicture }
        ],
        detailImg: [
          { required: true, message: "请上传图片", trigger: "change" },
          { validator: validateTemplatePicture }
        ],
        offShelfTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
          { validator: validateTemplateTime }
        ],
        purchaseLimit: [{ validator: validateNumEmpty }],
        specificationName: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateTemplateContent }
        ],
        specificationType: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateTemplateContent }
        ],
        venueFloor: [
          { required: true, message: "请选择楼层", trigger: "blur" },
          { validator: validateTemplateFloor }
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { validator: validateStringSpecial }
        ],
        stock: [
          { required: true, message: "请输入库存", trigger: "blur" },
          { validator: validateNumInt }
        ],
        shelfTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
          { validator: validateTemplateTime }
        ],
        floor: [
          {
            type: "array",
            required: true,
            message: "请选择楼层",
            trigger: "change"
          },
          { validator: validateTemplateFloor }
        ],
        referActivityName: [
          {
            required: true,
            message: "请选择活动",
            trigger: "change"
          },
          { validator: validateTemplateActivity }
        ]
      }
    };
  },
  mounted() {},
  methods: {
    initDialog() {
      if (this.dialogObj.id) {
        this.form.categoryId = this.dialogObj.form.categoryId;
        this.form.currentPrice = this.dialogObj.form.currentPrice;
        this.form.description = this.dialogObj.form.description;
        this.form.imgUrl = this.dialogObj.form.imgUrl;
        this.form.detailImg = this.dialogObj.form.detailImg;
        if (this.dialogObj.form.detail) {
          this.tableData = JSON.parse(this.dialogObj.form.detail);
        } else {
          this.tableData = {
            imageUrl: "",
            description: ""
          };
        }
        this.form.detail = "";
        this.form.isDraft = this.dialogObj.form.isDraft;
        this.form.productName = this.dialogObj.form.productName;
        this.form.specificationName = this.dialogObj.form.specificationName;
        this.form.specificationType = this.dialogObj.form.specificationType;
        this.form.referActivityId = this.dialogObj.form.referActivityId;
        // this.form.referActivityDate = this.dialogObj.form.referActivityDate;
        this.form.referActivityName = this.dialogObj.form.referActivityName;
        // if (this.dialogObj.form.referActivityId) {
        //   this.activity = this.dialogObj.form.referActivityId.split(","); //数据回显
        // } else {
        //   this.activity = [];
        // }
        this.form.productActivityList = this.dialogObj.form.productActivityList;
        // 回显数据格式转化
        var productAct = this.dialogObj.form.productActivityList;
        var productActArr = [];
        if (productAct.length > 0) {
          productAct.forEach(item => {
            item.activityTimes =
              typeof item.activityTimes == "string"
                ? item.activityTimes.split(",")
                : item.activityTimes; // 字符串转数组
            item.activityTimes.forEach(v => {
              var itemArr = [item.activityId, v];
              productActArr.push(itemArr);
            });
          });
        } else {
          productActArr = [];
        }
        this.productActivityList = productActArr;
        this.form.purchaseLimit = this.dialogObj.form.purchaseLimit;
        this.form.sort = this.dialogObj.form.sort;
        this.form.stock = this.dialogObj.form.totalStock;
        if (this.dialogObj.form.venueFloor) {
          this.form.venueFloor = this.dialogObj.form.venueFloor;
          this.floor = this.form.venueFloor.split(",").map(Number);
        } else {
          this.form.venueFloor = "";
          this.floor = [];
        }
        if (this.dialogObj.form.offShelfTime) {
          this.form.offShelfTime = this.dialogObj.form.offShelfTime;
          this.offTime = 1; //1 指定时间  2 长期不下架
        } else {
          this.form.offShelfTime = "";
          this.offTime = 2;
        }
        if (this.dialogObj.form.shelfTime) {
          this.form.shelfTime = this.dialogObj.form.shelfTime;
          this.onTime = 2; //1 立即上架  2 指定时间
        } else {
          this.onTime = 1;
          this.form.shelfTime = "";
        }
      } else {
        this.onTime = 1;
        this.offTime = 2;
        this.tableData = [
          {
            imageUrl: "",
            description: ""
          }
        ];
        this.form.categoryId = "";
        this.form.currentPrice = "";
        this.form.description = "";
        this.form.imgUrl = "";
        this.form.detailImg = "";
        this.form.detail = "";
        this.form.isDraft = "";
        this.form.offShelfTime = "";
        this.form.productName = "";
        this.form.specificationName = "";
        this.form.specificationType = "";
        this.form.referActivityId = "";
        // this.activity = [];
        // this.form.referActivityDate = "";
        this.form.productActivityList = "";
        this.productActivityList = [];
        this.form.referActivityName = "";
        this.form.purchaseLimit = "";
        this.form.shelfTime = "";
        this.form.sort = "";
        this.form.stock = "";
        this.form.venueFloor = "";
        this.floor = [];
      }
    },
    // 活动信息
    getActivityList() {
      getLocalActivityApi().then(res => {
        // 特许商品判断权限筛选
        // 查询是否有活动权限
        res = res.list;
        let getActivityId =
          JSON.parse(localStorage.getItem("mb_userInfo")).activityIds || "";
        if (getActivityId && getActivityId != "0") {
          // 单个活动用户
          getActivityId = getActivityId.split(","); // 字符串转数组
          // 活动权限筛选
          let activityArr = [];
          res.forEach(item => {
            if (getActivityId.indexOf(item.activityId) > -1) {
              activityArr.push(item);
            }
          });
          this.ActivityList = activityArr;
        } else {
          // 所有活动用户
          this.ActivityList = res;
        }
        // 判断回显的数据是否存在列表中
        // if (this.dialogObj.id) {
        //   this.activity.forEach((x, i) => {
        //     let findId = this.ActivityList.filter(item => {
        //       return item.activityId == x;
        //     });
        //     if (findId.length == 0) {
        //       let newArr = {
        //         activityName: this.dialogObj.form.referActivityName.split(",")[
        //           i
        //         ],
        //         activityStartDate: this.dialogObj.form.referActivityDate.split(
        //           ","
        //         )[i],
        //         activityId: x
        //       };
        //       this.ActivityList.push(newArr);
        //     }
        //   });
        // }
        // 替换规则为符合参数
        var json = [];
        this.ActivityList.forEach(item => {
          var newitem = {
            value: item.activityId,
            label: item.activityName
          };
          item.activityDates = JSON.parse(item.activityDates);
          var jsonItem = [];
          item.activityDates.forEach(v => {
            var vItem = {
              value: v.start,
              label: v.start
            };
            jsonItem.push(vItem);
          });
          newitem.activityDates = jsonItem;
          json.push(newitem);
        });
        this.ActivityList = json;
      });
    },
    // 活动选择
    handleActivity(val) {
      var newVal = [];
      // 数据处理
      val.forEach(item => {
        // 获取名字
        var name = "";
        this.ActivityList.forEach(n => {
          if (n.value == item[0]) {
            name = n.label;
          }
        });
        // 得出新项
        var newItem = {
          activityId: item[0],
          activityName: name,
          activityTimes: [item[1]]
        };
        var flag = false;
        // 判断父级是否存在,存在则加入场次
        newVal.forEach(v => {
          if (v.activityId == item[0]) {
            flag = true;
            v.activityTimes.push(item[1]);
          }
        });
        // 判断父级不存在
        if (!flag) {
          newVal.push(newItem);
        }
      });
      // 名字拼接字符串
      var stringName = [];
      var stringId = [];
      newVal.forEach(item => {
        stringName.push(item.activityName);
        stringId.push(item.activityId);
      });
      if (stringName.length > 0) {
        this.form.referActivityName = stringName.join(","); // 数组转字符串
        this.form.referActivityId = stringId.join(","); // 数组转字符串
      } else {
        this.form.referActivityName = "";
        this.form.referActivityId = "";
      }
      newVal.forEach(item => {
        item.activityTimes = item.activityTimes.join(","); // 数组转字符串
      });
      this.form.productActivityList = newVal;
    },
    productSelect() {
      var json = {
        categoryType: 2 // 2 特许
      };
      getProductSelectApi(json).then(res => {
        this.prouductSelect = res;
      });
    },
    handleTableDate() {},
    handleSuccess(val) {
      this.form.imgUrl = val;
    },
    handleSuccessDetail(val) {
      this.form.detailImg = val;
    },
    changeCheck(val) {
      this.form.venueFloor = val.join(",");
    },
    sub: _debounce(function(val) {
      this.goodStatus = val;
      this.form.detail = JSON.stringify(this.tableData);
      if (!this.form.sort) {
        this.form.sort = 999; // 默认排序码
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.dialogObj.show = false;
          if (this.form.referActivityName) {
            if (this.form.venueFloor) {
              if (
                this.form.shelfTime &&
                this.form.offShelfTime &&
                this.offTime == 1 &&
                this.onTime == 2
              ) {
                var shelfTime = null;
                var offShelfTime = null;
                if (this.dialogObj.id) {
                  shelfTime = new Date(this.form.shelfTime);
                  offShelfTime = new Date(this.form.offShelfTime);
                } else {
                  shelfTime = this.form.shelfTime;
                  offShelfTime = this.form.offShelfTime;
                }
                // this.dialogObj.show = false;
                if (shelfTime > offShelfTime) {
                  this.$message({
                    type: "warning",
                    message: "下架时间必须大于上架时间！"
                  });
                } else {
                  if (this.dialogObj.id) {
                    this.updateSub();
                  } else {
                    this.addSub();
                  }
                }
              } else {
                if (this.dialogObj.id) {
                  this.updateSub();
                } else {
                  this.addSub();
                }
              }
            } else {
              this.$message({
                type: "warning",
                message: "至少选择一个楼层！"
              });
            }
          } else {
            this.$message({
              type: "warning",
              message: "至少选择一个活动！"
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "必选项未填完！"
          });
        }
      });
    }),
    addSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (this.goodStatus == 1) {
        json.isDraft = 1; // 草稿
      }
      if (this.onTime == 1) {
        // 立即上架
        json.shelfTime = timeFormat.hoursTime(new Date());
        if (this.goodStatus == 2) {
          json.isDraft = 3; // 上架中
        }
      } else {
        json.shelfTime = timeFormat.hoursTime(this.form.shelfTime);
        if (this.goodStatus == 2) {
          json.isDraft = 2; // 待上架
        }
      }
      if (this.offTime == 2) {
        // 长期不下架
        json.offShelfTime = "";
      } else {
        json.offShelfTime = timeFormat.hoursTime(this.form.offShelfTime);
      }
      addGoodsInfoApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "添加成功！"
        });
      });
    },
    updateSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (this.goodStatus == 1) {
        json.isDraft = 1; // 草稿
      }
      if (this.onTime == 1) {
        // 立即上架
        json.shelfTime = timeFormat.hoursTime(new Date());
        if (this.goodStatus == 2) {
          json.isDraft = 3; // 上架中
        }
      } else {
        if (this.goodStatus == 2) {
          json.shelfTime = timeFormat.hoursTime(this.form.shelfTime);
          json.isDraft = 2; // 待上架
        }
      }
      if (this.offTime == 2) {
        // 长期不下架
        json.offShelfTime = "";
      } else {
        json.offShelfTime = timeFormat.hoursTime(this.form.offShelfTime);
      }
      json.id = this.dialogObj.id;
      delete json.stock;
      updateGoodsInfoApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "修改成功！"
        });
      });
    }
  },
  watch: {
    "dialogObj.show"(val) {
      if (val) {
        this.initDialog();
        this.getActivityList();
        this.productSelect();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.operate-footer {
  text-align: center;
}
</style>
<style>
.el-select-dropdown.el-popper.is-multiple.multi-cascader-style {
  width: 500px !important;
  min-width: 500px !important;
}
.multi-cascader-style ol,
.multi-cascader-style .ground ul,
.el-select-dropdown.el-popper.is-multiple.multi-cascader-style .li-style {
  width: 260px !important;
}
.el-select-dropdown.el-popper.is-multiple.multi-cascader-style .floor-item {
  width: 240px !important;
}
.multi-cascader-style .floor-position-left-2 {
  left: 260px !important;
}
</style>
